import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, InputNumber } from 'antd';
import { useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { deptListTree,deptAdd } from '@/services/system/departmentmanage';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  form: {
    maxWidth: '800px',
    margin: '0 auto',
  },
  formItem: {
    marginBottom: '24px',
    '& .ant-form-item-label': {
      fontWeight: 500,
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '40px',
  },
  formLayout: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '24px',
  },
  fullWidth: {
    gridColumn: '1 / -1',
  },
}));

interface DeptTreeItem {
  id: string;
  fatherDepartmentId: string | null;
  departmentName: string;
  departmentType: number;
  description: string;
  sort: number;
  status: number;
  children?: DeptTreeItem[];
}

const DepartmentAdd: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [deptTreeData, setDeptTreeData] = useState<DeptTreeItem[]>([]);

  // 获取部门树形数据
  useEffect(() => {
    const fetchDeptTree = async () => {
      try {
        const response = await deptListTree();
        if (response.code === 200 && response.success) {
          setDeptTreeData(response.data);
        } else {
          message.error('获取部门列表失败');
        }
      } catch (error) {
        console.error('获取部门列表失败:', error);
        message.error('获取部门列表失败');
      }
    };

    fetchDeptTree();
  }, []);

  // 递归渲染部门选项
  const renderDeptOptions = (deptList: DeptTreeItem[]) => {
    return deptList.map(dept => {
      if (dept.children && dept.children.length > 0) {
        return (
          <Select.OptGroup key={dept.id} label={dept.departmentName}>
            <Select.Option value={dept.id} key={dept.id}>
              {dept.departmentName}
            </Select.Option>
            {renderDeptOptions(dept.children)}
          </Select.OptGroup>
        );
      }
      return (
        <Select.Option value={dept.id} key={dept.id}>
          {dept.departmentName}
        </Select.Option>
      );
    });
  };

  const onFinish = async (values: any) => {
    try {
      const params = {
            ...values
      };
      const response = await deptAdd(params);
      if (response.code === 200) {
        message.success('新增部门成功');
        navigate('/system/departmentmanage');
      } else {
        message.error(response.msg || '新增部门失败');
      }

    } catch (error) {
      console.error('提交失败:', error);
      message.error('新增部门失败');
    }
  };

  const handleCancel = () => {
    navigate('/system/departmentmanage');
  };

  return (
    <PageContainer
      header={{
        title: '部门新增',
      }}
    >
      <div className={styles.container}>
        <Card className={styles.card}>
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            className={styles.form}
          >
            <div className={styles.formLayout}>
              <Form.Item
                name="departmentName"
                label="部门名称："
                rules={[{ required: true, message: '请输入部门名称' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入部门名称" />
              </Form.Item>

              <Form.Item
                name="departmentType"
                label="部门类型："
                rules={[{ required: true, message: '请选择部门类型' }]}
                className={styles.formItem}
              >
                <Select placeholder="请选择部门类型">
                  <Select.Option value="0">0</Select.Option>
                  <Select.Option value="1">1</Select.Option>
                  <Select.Option value="2">2</Select.Option>
                  {/* 可以根据需要添加更多选项 */}
                </Select>
              </Form.Item>

              <Form.Item
                name="fatherDepartmentId"
                label="上级部门："
                rules={[{ required: true, message: '请选择上级部门' }]}
                className={styles.formItem}
              >
                <Select
                  placeholder="请选择上级部门"
                  allowClear
                  showSearch
                  optionFilterProp="children"
                >
                  <Select.Option value="">顶级部门</Select.Option>
                  {renderDeptOptions(deptTreeData)}
                </Select>
              </Form.Item>

              <Form.Item
                name="sort"
                label="部门排序："
                rules={[{ required: true, message: '请输入部门排序' }]}
                className={styles.formItem}
              >
                <InputNumber min={1} placeholder="请输入部门排序" style={{ width: '100%' }} />
              </Form.Item>

              <Form.Item
                name="description"
                label="部门描述："
                className={`${styles.formItem} ${styles.fullWidth}`}
              >
                <Input.TextArea
                  rows={4}
                  placeholder="请输入部门描述"
                />
              </Form.Item>
            </div>

            <div className={styles.buttonGroup}>
              <Button onClick={handleCancel}>
                返回
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </div>
          </Form>
        </Card>
      </div>
    </PageContainer>
  );
};

export default DepartmentAdd;

